import React, { Component, Fragment } from 'react';
import { message, Spin } from 'antd';
import propTypes from 'prop-types';
import { checkAuth } from './api.js';
import { Redirect } from 'react-router-dom'
import { getUserInfo } from "../../utils/CommonUtils";
import qs from 'qs';
import ExceptionPage from '../../../commons/components/ExceptionPage/index.jsx';

const SsoHoc = WrappedComponent => {
  return class extends Component {

    state = {
      componentType: 'loading'
    }

    componentDidMount() {
      const { history } = this.props;
      const userInfo = getUserInfo() || {};
      const {sessionId="", accessToken=""} = userInfo;
      const queryObj = qs.parse(window.location.href.split('?')[1]);
      if (queryObj._s) {
        checkAuth({
          sessionId: queryObj._s,
          url: history.location.pathname,
          appCode: process.env.REACT_APP_MODULE_NAME
        })
        .then(res => {
          const { statusCode, data } = res;
          let componentType = statusCode;
          // if (componentType == 200) {
          sessionStorage.removeItem('Authorization');
          sessionStorage.removeItem('_s');
          if (data) {
            sessionStorage.setItem('Authorization', JSON.stringify(data[0]));
            sessionStorage.setItem('_s', data[0].sessionId);
          }
          // }
          this.setState({
            componentType
          });
        })
        .catch(err => {
          this.setState({
            componentType: '500'
          });
        })
      } else {
        let componentType = '200';
        if (!accessToken) {
          componentType = '401';
        }
        this.setState({
          componentType,
        });
      }

    }

    getRenderComponent = (type) => {
      const components = {
        "loading": (<Spin spinning={true}></Spin>),
        "401": (<Redirect to={"/"}/>),
        "403": (<ExceptionPage type="403"/>),
        "200": (<WrappedComponent {...this.props}/>),
        "500": (<ExceptionPage type="500"/>)
      };

      return components[type];
    }

    getChildren = () => {
      const { componentType } = this.state;
      return this.getRenderComponent(componentType);
    }

    render() {
      return (
        <Fragment>
          {this.getChildren()}
        </Fragment>
      );
    }
  }
}

export default SsoHoc;
